﻿
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace MvvmFx.Common.Helpers
{
    /// <summary>
    /// The DesignTime helper class - used to specify DesignTime text for Silverlight controls
    /// </summary>
    public static class DesignTime
    {
        /// <summary>
        /// Register the attached dependency property TextProperty.
        /// </summary>
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.RegisterAttached(
                "Text",
                typeof(string),
                typeof(DesignTime),
                new PropertyMetadata(string.Empty, TextPropertyChanged));

        /// <summary>
        /// Get the text.
        /// </summary>
        /// <param name="textBox">The textbox to get the text from.</param>
        /// <returns>The text returned from the textbox.</returns>
        [EditorBrowsable(EditorBrowsableState.Always),
         Category("Common Properties"),
         Description("Gets or sets the Design-Time Text property")]
        public static string GetText(FrameworkElement textBox)
        {
            return (string)textBox.GetValue(TextProperty);
        }

        /// <summary>
        /// Set the text for the textbox.
        /// </summary>
        /// <param name="textBox">The text for the textbox.</param>
        /// <param name="value">The text to set for the text box.</param>
        public static void SetText(FrameworkElement textBox, string value)
        {
            textBox.SetValue(TextProperty, value);
        }

        /// <summary>
        /// Occurs when the <see cref="TextPropertyChanged"/> changes set the text for the text box element. 
        /// </summary>
        /// <param name="o">The <see cref="DependencyObject"/> object that fired the event.</param>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> event fired.</param>
        private static void TextPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = o as TextBox;
            if (textBox != null)
            {
                if (DesignerProperties.GetIsInDesignMode(textBox))
                {
                    if (e.NewValue != null)
                    {
                        string text = e.NewValue.ToString();
                        textBox.Text = text;
                    }
                }
            }

            TextBlock textBlock = o as TextBlock;
            if (textBlock != null)
            {
                if (DesignerProperties.GetIsInDesignMode(textBlock))
                {
                    if (e.NewValue != null)
                    {
                        string text = e.NewValue.ToString();
                        textBlock.Text = text;
                    }
                }
            }
        }
    }
}